package me.zhengjie.kwService.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.constant.KwConstant;
import me.zhengjie.kwService.PhoneStudentService;
import me.zhengjie.mapper.ExamMapper;
import me.zhengjie.mapper.ExamRoomMapper;
import me.zhengjie.mapper.ExamStudentMapper;
import me.zhengjie.pojo.dto.FindStudentExamDto;
import me.zhengjie.pojo.dto.PhoneScoreDto;
import me.zhengjie.pojo.entity.Exam;
import me.zhengjie.pojo.entity.ExamRoom;
import me.zhengjie.pojo.entity.ExamStudent;
import me.zhengjie.pojo.entity.Student;
import me.zhengjie.pojo.vo.FindStudentExamVo;
import me.zhengjie.util.AssertUtils;
import me.zhengjie.util.BaseResponse;
import me.zhengjie.util.RedisUtils;
import me.zhengjie.util.ruoyiexcel.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Long
 * @date 2021/7/6 11:07
 */
@Service
@Slf4j
public class PhoneStudentServiceImpl implements PhoneStudentService {

    @Autowired
    private ExamMapper examMapper;
    @Autowired
    private ExamStudentMapper examStudentMapper;
    @Autowired
    private ExamRoomMapper examRoomMapper;

    @Override
    public BaseResponse findStudentExam(FindStudentExamDto dto, HttpServletRequest request) {
        Student student = RedisUtils.INSTANCE.getLoginInfo(request.getHeader(KwConstant.USERTOKEN), Student.class);
        /*String userToken = request.getHeader(KwConstant.USERTOKEN);
        String loginUser = RedisUtils.INSTANCE.get(userToken);
        Student student = JSON.parseObject(loginUser, Student.class);*/
        String studentName = student.getNameCn();
        Integer studentId = student.getId();
        log.info("学生姓名：" + studentName);
        log.info("学生Id：" + studentId);
        /*如果传入了考试id，那么查询单个考试详情信息(包括考试信息、考场信息、和考生信息),先查询考试信息，再根据考生id和考试id查询考生安排表的考场id再查出考场名称地点*/
        if (dto.getId() != null) {
            FindStudentExamVo vo = new FindStudentExamVo();
            Exam exam = examMapper.selectById(dto.getId());
            BeanUtils.copyProperties(exam, vo);
            vo.setStudentName(studentName);
            if (studentId != null) {
                QueryWrapper<ExamStudent> wrapper = new QueryWrapper<>();
                wrapper.eq("student_id", studentId).eq("exam_id", dto.getId());
                ExamStudent examStudent = examStudentMapper.selectOne(wrapper);
                if (examStudent != null) {
                    vo.setExamStudentId(examStudent.getId());
                    vo.setExaminee(examStudent.getExaminee());
                    vo.setScore(StringUtils.isNotBlank(examStudent.getScore()) ? examStudent.getScore() : "");
                    Integer examRoomId = examStudent.getExamRoomId();
                    if (examRoomId != null) {
                        ExamRoom examRoom = examRoomMapper.selectById(examRoomId);
                        if (examRoom != null) {
                            vo.setExamRoomNameCn(examRoom.getNameCn());
                            vo.setExamRoomAddress(examRoom.getAddress());
                        }
                    }
                }
            }
            /*考生只能查看考生须知，监考规则只能教师查看*/
            vo.setTearcherNotes(null);
            return BaseResponse.ok(vo);
        }

        if (studentId != null) {
            /*如考试id为空，查询全部考试信息*/
            QueryWrapper<ExamStudent> studentWrapper = new QueryWrapper<>();
            studentWrapper.eq("student_id", studentId);
            List<ExamStudent> list = examStudentMapper.selectList(studentWrapper);
            LinkedList<Integer> examIds = new LinkedList<>();
            if (list != null && list.size() > 0) {
                for (ExamStudent examStudent : list) {
                    if (examStudent.getExamId() != null) {
                        examIds.add(examStudent.getExamId());
                    }
                }
            }
            if (!examIds.isEmpty()) {
                QueryWrapper<Exam> wrapper = new QueryWrapper<>();
                wrapper.in("id", examIds);
                if ("1".equals(dto.getStatus())) {
                    wrapper.eq("status", dto.getStatus());
                }
                List<Exam> exams = examMapper.selectList(wrapper);
                LinkedList<FindStudentExamVo> voList = new LinkedList<>();
                for (Exam exam : exams) {
                    FindStudentExamVo vo = new FindStudentExamVo();
                    BeanUtils.copyProperties(exam, vo);
                    vo.setStudentName(studentName);
                    for (ExamStudent examStudent : list) {
                        if (examStudent.getExamId().equals(exam.getId())) {
                            vo.setScore(StringUtils.isNotBlank(examStudent.getScore()) ? examStudent.getScore() : "");
                            vo.setExamStudentId(examStudent.getId());
                        }
                    }
                    voList.add(vo);
                }
                for (FindStudentExamVo findStudentExamVo : voList) {
                    findStudentExamVo.setTearcherNotes(null);
                }
                return BaseResponse.ok("查询成功", voList);
            }
            return BaseResponse.ok();

        }
        return BaseResponse.failed();
    }

    @Override
    public ExamStudent findStudentScore(Integer id) {
        AssertUtils.isNotNull(id, "考试id不可为空");
        ExamStudent examStudent = examStudentMapper.selectById(id);
        return examStudent;
    }

    @Override
    public void saveScoreStatus(PhoneScoreDto dto) {
        AssertUtils.isNotNull(dto, "申请信息不可为空");
        UpdateWrapper<ExamStudent> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", dto.getId())
                .set(StringUtils.isNotBlank(dto.getScoreReviewReson()), "score_review_reson", dto.getScoreReviewReson())
                .set(StringUtils.isNotBlank(dto.getScoreStatus()), "score_status", dto.getScoreStatus())
                .set(StringUtils.isNotBlank(dto.getStatus()), "status", dto.getStatus())
                .set(StringUtils.isNotBlank(dto.getStatusProveReason()), "status_prove_reason", dto.getStatusProveReason())
                .set("update_time", new Date());
        Exam exam = new Exam();
        BeanUtils.copyProperties(dto, exam);
        examStudentMapper.update(null, updateWrapper);
    }
}
